﻿#include "Worker.h"
#include "Utils/Log.h"
#include "Utils/Common.h"
#include "Utils/AlgUtils.h"
#include "Scheduler.h"
#include "Analyzer.h"
#include "Control.h"
#include "Algorithm.h"
#include "AvPullStream.h"
#include "AvPushStream.h"
#include "GenerateAlarmVideo.h"
#include "Frame.h"
#include "GenerateAlarmImage.h"
#include <filesystem>
#include <iomanip>
#include <fstream>


extern "C" {
#include "libswscale/swscale.h"
#include <libavutil/imgutils.h>
#include <libswresample/swresample.h>
}

namespace AVSAnalyzer 
{
    Worker::Worker(Scheduler* scheduler, Control* control) :
        mScheduler(scheduler),
        mControl(new Control(*control)),
        mPullStream(nullptr),
        mPushStream(nullptr),
        mAnalyzer(nullptr),
        mState(false),
        mAlarmImageGenerator(nullptr)
    {
        mControl->startTimestamp = getCurTimestamp();
        // 从调度器获取配置信息
        Config* config = mScheduler->getConfig();
        mAlarmImageGenerator = new GenerateAlarmImage(mControl->code, mControl->algorithmCode, *config);

        if (FT_Init_FreeType(&mFtLibrary)) 
        {
            LOGE("Could not init freetype library");
        } 
        else if (FT_New_Face(mFtLibrary, "Res/simhei.ttf", 0, &mFtFace)) 
        {
            LOGE("Could not load font");
        } 
        else 
        {
            FT_Set_Pixel_Sizes(mFtFace, 0, 24);  // 设置字体大小
            mFtValid = true;
        }
    }

    Worker::~Worker()
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));

        mState = false;// 将执行状态设置为false

        for (auto th : mThreads) 
        {
            th->join();
        }

        for (auto th : mThreads) 
        {
            delete th;
            th = nullptr;
        }
        mThreads.clear();
        clearAlarmVideoFrameQ();

        if (mPullStream) 
        {
            delete mPullStream;
            mPullStream = nullptr;
        }
        if (mPushStream) 
        {
            delete mPushStream;
            mPushStream = nullptr;
        }

        if (mAnalyzer) 
        {
            delete mAnalyzer;
            mAnalyzer = nullptr;
        }

        if (mControl) 
        {
            delete mControl;
            mControl = nullptr;
        }
        //最有一步释放mFramePool
        if (mVideoFramePool) 
        {
            delete mVideoFramePool;
            mVideoFramePool = nullptr;
        }

        if (mAlarmImageGenerator) 
        {
            delete mAlarmImageGenerator;
            mAlarmImageGenerator = nullptr;
        }

        if (mFtValid) 
        {
            FT_Done_Face(mFtFace);
            FT_Done_FreeType(mFtLibrary);
        }
    }

    bool Worker::start(std::string& msg) 
    {
        this->mPullStream = new AvPullStream(this);
        if (this->mPullStream->connect()) 
        {
            if (mControl->pushStream) 
            {
                this->mPushStream = new AvPushStream(this);
                if (this->mPushStream->connect()) 
                {
                    // success
                    LOGI("push stream connect success");
                }
                else 
                {
                    msg = "pull stream connect success, push stream connect error";
                    return false;
                }
            }
            else 
            {
                // success
                LOGI("pull stream connect success");
            }
        }
        else 
        {
            msg = "pull stream connect error";
            return false;
        }

        int videoBgrSize = mControl->videoHeight * mControl->videoWidth * mControl->videoChannel;
        this->mVideoFramePool = new FramePool(videoBgrSize);
        this->mAnalyzer = new Analyzer(mScheduler, mControl);

        mState = true;// 将执行状态设置为true
        // 启动拉流线程
        std::thread* th = new std::thread(AvPullStream::readThread, this->mPullStream);
        mThreads.push_back(th);

        // 启动解码线程
        th = new std::thread(Worker::decodeVideoThread, this);
        mThreads.push_back(th);
        // 启动报警视频生成线程
        th = new std::thread(Worker::generateAlarmThread, this);
        mThreads.push_back(th);

        if (mControl->pushStream) 
        {
            if (mControl->videoIndex > -1) 
            {
                // 启动推流线程
                th = new std::thread(AvPushStream::encodeVideoThread, this->mPushStream);
                mThreads.push_back(th);
            }
        }
        // 启动所有线程
        for (auto th : mThreads) 
        {
            th->native_handle();
        }

        return true;
    }
    // 获取工作线程状态
    bool Worker::getState() 
    {
        return mState;
    }
    // 移除工作线程
    void Worker::remove() 
    {
        mState = false;
        mScheduler->removeWorker(mControl);
    }
    // 报警视频生成线程
    void Worker::generateAlarmThread(void* arg) 
    {
        Worker* worker = (Worker*)arg;
        worker->handleGenerateAlarm();
    }

    void Worker::handleGenerateAlarm() 
    {
        int width = mControl->videoWidth;
        int height = mControl->videoHeight;
        int channels = mControl->videoChannel;
        Frame* videoFrame = nullptr; // 未编码的视频帧（bgr格式）
        std::queue<Frame* > cacheV;
        int prefix_size = 30; //75 = 25 * 3，事件发生前缓存3秒的数据，1张压缩图片100kb

        bool happening = false;// 当前是否正在发生报警行为
        std::queue<Frame* > happenV;
        int  total_size = 60;//报警总帧数最大长度

        int64_t last_alarm_timestamp = 0;// 上一次报警的时间戳
        int64_t t1, t2 = 0;

        while (getState())
        {
            if (getAlarmVideoFrame(videoFrame)) 
            {
                if (happening && cacheV.empty()) 
                {
                    // 报警事件已经发生，正在进行中
                    // 将当前帧添加到happenV队列
                    happenV.push(videoFrame);
                    // 如果happenV队列中的帧数达到total_size，则生成报警视频
                    if (happenV.size() >= total_size) 
                    {
                        last_alarm_timestamp = getCurTimestamp();

                        //产生报警视频
                        Alarm* alarm = new Alarm(
                            height,
                            width,
                            mControl->videoFps,
                            last_alarm_timestamp,prefix_size,
                            mControl->code.data()
                        );
                        // 将happenV队列中的帧添加到alarm中
                        while (!happenV.empty())
                        {
                            Frame * p = happenV.front();
                            happenV.pop();
                            alarm->frames.push_back(p);
                        }
                        // 将alarm添加到调度器中
                        mScheduler->addAlarm(alarm);
                        happening = false;
                    }
                }
                else {
                    // 暂未发生报警事件
                    if (!cacheV.empty() && cacheV.size() >= prefix_size) 
                    {
                        //缓存帧超过容量上限 prefix_size
                        Frame* head = cacheV.front();
                        cacheV.pop();
                        mVideoFramePool->giveBack(head);
                    }
                    cacheV.push(videoFrame);

                    if (videoFrame->happen &&
                        cacheV.size() >= prefix_size &&
                        (getCurTimestamp() - last_alarm_timestamp) > mControl->minInterval) 
                    {
                        //满足报警开始条件
                        happening = true;
                        // 将cacheV队列中的帧添加到happenV队列
                        while (!cacheV.empty())
                        {
                            Frame * p = cacheV.front();
                            cacheV.pop();
                            happenV.push(p);
                        }        
                    }
                }
            }
            else 
            {   
                // 如果无法获取视频帧，则等待5ms
                std::this_thread::sleep_for(std::chrono::milliseconds(5));
            }
        }

        while (!happenV.empty())
        {
            Frame * p = happenV.front();
            happenV.pop();
            delete p;
            p = nullptr;            
        }
        while (!cacheV.empty())
        {
            Frame* p = cacheV.front();
            cacheV.pop();
            delete p;
            p = nullptr;
        }
    }
    void Worker::decodeVideoThread(void* arg) 
    {
        Worker* worker = (Worker*)arg;
        worker->handleDecodeVideo();
    }

    void Worker::handleDecodeVideo() 
    {   
        int width = mPullStream->mVideoCodecCtx->width;
        int height = mPullStream->mVideoCodecCtx->height;

        AVPacket pkt;           // 未解码的视频帧
        int      pktQSize = 0;  // 未解码视频帧队列当前长度

        AVFrame* frame_yuv420p = av_frame_alloc();                      // pkt->解码->frame
        // 设置 frame_yuv420p 的参数
        frame_yuv420p->format = mPullStream->mVideoCodecCtx->pix_fmt;  // 设置像素格式
        frame_yuv420p->width  = mPullStream->mVideoCodecCtx->width;    // 设置宽度
        frame_yuv420p->height = mPullStream->mVideoCodecCtx->height;   // 设置高度
        // 分配 frame_yuv420p 的缓冲区
        int ret = av_frame_get_buffer(frame_yuv420p, 32);  // 32 是字节对齐
        if (ret < 0) 
        {
            fprintf(stderr, "Could not allocate the video frame data\n");
            return;
        }

        AVFrame* frame_bgr = av_frame_alloc();

        int frame_bgr_buff_size = av_image_get_buffer_size(AV_PIX_FMT_BGR24, width, height, 1);
        uint8_t* frame_bgr_buff = (uint8_t*)av_malloc(frame_bgr_buff_size);
        av_image_fill_arrays(frame_bgr->data, frame_bgr->linesize, frame_bgr_buff, AV_PIX_FMT_BGR24, width, height, 1);

        SwsContext* sws_ctx_yuv420p2bgr = sws_getContext(width, height,
            mPullStream->mVideoCodecCtx->pix_fmt,
            mPullStream->mVideoCodecCtx->width,
            mPullStream->mVideoCodecCtx->height,
            AV_PIX_FMT_BGR24,
            SWS_BICUBIC, nullptr, nullptr, nullptr);

        int fps = mControl->videoFps;

        //算法检测参数start
        bool cur_is_check = false;                      // 当前帧是否进行算法检测
        int  continuity_check_count = 0;                // 当前连续进行算法检测的帧数
        int  continuity_check_max_time = 6000;          // 连续进行算法检测，允许最长的时间。单位毫秒
        int64_t continuity_check_start = getCurTime();  // 单位毫秒
        int64_t continuity_check_end = 0;
        //算法检测参数end

        ret = -1;
        int64_t frameCount = 0;
        bool happen = false;
        float happenScore = 0.0;
        std::vector<DetectObject> happenDetects;
        // 添加抽帧相关变量
        const int FRAME_INTERVAL = 1;  // 每隔3帧进行一次检测
        bool needDetect = false;

        while (getState())
        {
            if (mPullStream->getVideoPkt(pkt, pktQSize)) 
            {
                if (mControl->videoIndex > -1) 
                {
                    ret = avcodec_send_packet(mPullStream->mVideoCodecCtx, &pkt);
                    if (ret == 0) 
                    {
                        // 解码
                        ret = avcodec_receive_frame(mPullStream->mVideoCodecCtx, frame_yuv420p);
                        if (ret == 0) 
                        {
                            frameCount++;

                            // 判断是否需要进行检测
                            needDetect = (frameCount % FRAME_INTERVAL == 0);

                            // frame（yuv420p） 转 frame_bgr
                            sws_scale(sws_ctx_yuv420p2bgr,
                                frame_yuv420p->data, frame_yuv420p->linesize, 0, height,
                                frame_bgr->data, frame_bgr->linesize);

                            cv::Mat image(mControl->videoHeight, mControl->videoWidth, CV_8UC3, frame_bgr->data[0]);

                            happen = false;
                            happenScore = 0.0;

                            if (pktQSize <= 1 && needDetect) 
                            {
                                // 只在需要检测的帧上进行算法推理
                                cur_is_check = mAnalyzer->handleVideoFrame(frameCount, image, happenDetects, happen, happenScore);
                                if (cur_is_check) 
                                {
                                    continuity_check_count += 1;
                                }
                            }
                            else 
                            {
                                // 非检测帧，保持上一帧的检测结果
                                cur_is_check = false;
                            }

                            continuity_check_end = getCurTime();
                            // 如果连续进行算法检测的时间超过continuity_check_max_time，则计算fps
                            if (continuity_check_end - continuity_check_start > continuity_check_max_time) 
                            {
                                mControl->checkFps = float(continuity_check_count) / (float(continuity_check_end - continuity_check_start) / 1000);
                                continuity_check_count = 0;
                                continuity_check_start = getCurTime();
                            }

                            //绘制start
                            cv::polylines(image, mControl->recognitionRegion_points, mControl->recognitionRegion_points.size(), cv::Scalar(0, 0, 255), 4, 8);//绘制多边形
                            if (happenDetects.size() > 0) {
                                int x1, y1, x2, y2;
                                for (size_t i = 0; i < happenDetects.size(); i++)
                                {
                                    x1 = happenDetects[i].x1;
                                    y1 = happenDetects[i].y1;
                                    x2 = happenDetects[i].x2;
                                    y2 = happenDetects[i].y2;

                                    // 根据class_id选择颜色（更合理的区分方式）
                                    //std::hash<std::string> hasher;
                                    int color_idx = ((happenDetects[i].class_id) % AVSAnalyzer::COLORS.size());
                                    cv::Scalar color = AVSAnalyzer::COLORS[color_idx];

                                    // 计算线宽（将原来的值减小）
                                    int line_width = 1 * std::min(image.cols, image.rows) / 180;
                                    line_width = 3; //std::min(line_width, 3);  // 确保最小为1像素

                                    //绘制得分和目标class_name
                                    std::string class_name = happenDetects[i].class_name;
                                    float       class_score = happenDetects[i].class_score;
                                    std::stringstream class_score_ss;
                                    class_score_ss << std::fixed << std::setprecision(0) << (class_score*100.0f);
                                    std::string title = class_name + ":" + class_score_ss.str() + "%";

                                    // 绘制检测框
                                    cv::rectangle(image, 
                                                cv::Rect(x1, y1, (x2 - x1), (y2 - y1)),
                                                color,
                                                line_width,             // 使用更细的线宽
                                                cv::LINE_8,            // 8-connected line
                                                0);

                                    int h = y2 - y1;
                                    int font_size = 6 * std::min(image.cols, image.rows) / 180;
                                    
                                    // 计算文本位置 - 放在框的左上方
                                    int text_x = x1;
                                    int text_y = y1 - 5;  // 向上偏移以确保文字在框外

                                    // 验证输入是否为有效UTF-8
                                    if (!AlgUtils::isValidUtf8(title)) {
                                        LOGE("Invalid UTF-8 sequence in title: %s", title.c_str());
                                        return;
                                    }
                    
                                    if(mFtValid)
                                    {
                                        // 计算文本实际尺寸
                                        int text_width = 0;
                                        int text_height = 0;
                                        calculateTextSize(title, text_width, text_height);
                                        
                                        // 添加适当的内边距
                                        int padding = 4;
                                        
                                        // 首先绘制与目标框同色的背景
                                        cv::Rect bg_rect(
                                            text_x - padding, 
                                            text_y - text_height - padding,
                                            text_width + (padding * 2),  // 使用计算得到的宽度加上内边距
                                            text_height + (padding * 2)  // 使用计算得到的高度加上内边距
                                        );
                                        
                                        cv::rectangle(image, bg_rect, color, -1);  // -1表示填充矩形
                                        
                                        drawChineseText(image, title, text_x, text_y, cv::Scalar(0, 0, 0));  // 文字黑色
                                    }
                                    else
                                    {
                                        cv::putText(image,
                                                title,
                                                cv::Point(text_x, text_y),
                                                cv::FONT_HERSHEY_SIMPLEX,
                                                font_size / 60.0f,
                                                color,
                                                line_width);
                                    }
                                }
                            }
                            // 绘制算法id
                            cv::putText(image, mControl->algorithmCode, cv::Point(20, 80), cv::FONT_HERSHEY_COMPLEX, 2, cv::Scalar(0, 0, 255), 2);
                            std::stringstream fps_stream;
                            fps_stream << std::setprecision(4) << mControl->checkFps;
                            std::string fps_title = "checkfps:" + fps_stream.str();
                            // 绘制fps
                            cv::putText(image, fps_title, cv::Point(20, 140), cv::FONT_HERSHEY_COMPLEX, 2, cv::Scalar(0, 0, 255), 1, cv::LINE_AA);
                            //绘制end
     
                            if (mControl->pushStream) 
                            {
                                //需要推算法实时流
                                int size = mPushStream->getVideoFrameQSize();
                                if (size > 3) {
                                    mPushStream->clearVideoFrameQueue();
                                }
                                Frame* frame = mVideoFramePool->gain();
                                frame->setBuf(frame_bgr->data[0], frame_bgr_buff_size);
                                frame->happen = happen;
                                frame->happenScore = happenScore;
                                mPushStream->addVideoFrame(frame);        
                            }

                            // 保存报警图片
                            if (happen) 
                            {
                                mAlarmImageGenerator->saveAlarmImage(image, happenScore);
                            }

                            //添加合成报警视频帧start
                            int size = getAlarmVideoFrameQSize();
                            if (size > 3) 
                            {
                                this->clearAlarmVideoFrameQ();
                            }
                         
                            Frame* frame = mVideoFramePool->gain();
                            frame->setBuf(frame_bgr->data[0], frame_bgr_buff_size);
                            frame->happen = happen;
                            frame->happenScore = happenScore;
                            this->addAlarmVideoFrameQ(frame);                
                            //添加合成报警视频帧end                           
                        }
                        // else if( ret == AVERROR(EAGAIN))
                        // {
                        //     continue;
                        // }    
                        // else if (ret == AVERROR_EOF) {
                        //     // End of stream reached
                        //     LOGI("End of video stream reached");
                        //     break;
                        // }                    
                        else 
                        {
                            LOGE("avcodec_receive_frame error : ret=%d", ret);
                        }
                    }
                    else 
                    {
                        LOGE("avcodec_send_packet error : ret=%d", ret);
                    }
                }
                // 队列获取的pkt，必须释放!!!
                //av_free_packet(&pkt);//过时
                av_packet_unref(&pkt);
            }
            else 
            {
                // 如果无法获取视频帧，则等待1ms,可以减少cpu占用
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
        }

        av_frame_free(&frame_yuv420p);
        //av_frame_unref(frame_yuv420p);
        frame_yuv420p = NULL;

        av_frame_free(&frame_bgr);
        //av_frame_unref(frame_bgr);
        frame_bgr = NULL;

        av_free(frame_bgr_buff);
        frame_bgr_buff = NULL;

        sws_freeContext(sws_ctx_yuv420p2bgr);
        sws_ctx_yuv420p2bgr = NULL;
    }

    void Worker::drawChineseText(cv::Mat& img, const std::string& text, int x, int y, cv::Scalar color) 
    {
        if (!mFtValid) {
            LOGE("FreeType not initialized properly");
            return;
        }

        FT_GlyphSlot slot = mFtFace->glyph;
        
        // 将UTF-8字符串转换为Unicode码点
        std::vector<uint32_t> unicode_chars;
        try {
            for (size_t i = 0; i < text.length();) {
                uint32_t unicode = 0;
                unsigned char c = text[i];
                
                if ((c & 0x80) == 0) {
                    // ASCII字符
                    unicode = c;
                    i += 1;
                } else if ((c & 0xE0) == 0xC0) {
                    // 2字节UTF-8
                    if (i + 1 >= text.length()) break;
                    unicode = ((c & 0x1F) << 6) | (text[i + 1] & 0x3F);
                    i += 2;
                } else if ((c & 0xF0) == 0xE0) {
                    // 3字节UTF-8
                    if (i + 2 >= text.length()) break;
                    unicode = ((c & 0x0F) << 12) | 
                             ((text[i + 1] & 0x3F) << 6) | 
                             (text[i + 2] & 0x3F);
                    i += 3;
                } else {
                    // 跳过无效字符
                    i += 1;
                    continue;
                }
                unicode_chars.push_back(unicode);
            }
        } catch (const std::exception& e) {
            LOGE("Error parsing UTF-8 string: %s", e.what());
            return;
        }

        // 创建一个临时图像用于文字渲染
        cv::Mat text_overlay = cv::Mat::zeros(img.size(), CV_8UC4);
        int baseline_x = x;
        int baseline_y = y;

        // 渲染每个字符
        for (uint32_t unicode : unicode_chars) {
            // 加载字形
            if (FT_Load_Char(mFtFace, unicode, FT_LOAD_RENDER)) {
                LOGE("Failed to load glyph for unicode: %u", unicode);
                continue;
            }

            // 获取字形位图
            FT_Bitmap& bitmap = slot->bitmap;
            
            // 计算字形位置
            int glyph_x = baseline_x + slot->bitmap_left;
            int glyph_y = baseline_y - slot->bitmap_top;

            // 确保在图像范围内
            if (glyph_x >= 0 && glyph_y >= 0 && 
                glyph_x + bitmap.width <= img.cols && 
                glyph_y + bitmap.rows <= img.rows) {
                
                // 将FreeType位图转换为OpenCV Mat
                cv::Mat glyph_bitmap(bitmap.rows, bitmap.width, CV_8UC1);
                memcpy(glyph_bitmap.data, bitmap.buffer, bitmap.rows * bitmap.width);

                // 为每个字形创建BGRA图像
                cv::Mat glyph_bgra = cv::Mat::zeros(bitmap.rows, bitmap.width, CV_8UC4);
                
                // 设置颜色和alpha通道
                for (int i = 0; i < bitmap.rows; i++) {
                    for (int j = 0; j < bitmap.width; j++) {
                        uchar alpha = glyph_bitmap.at<uchar>(i, j);
                        if (alpha > 0) {
                            glyph_bgra.at<cv::Vec4b>(i, j) = cv::Vec4b(
                                color[0], // B
                                color[1], // G
                                color[2], // R
                                alpha    // A
                            );
                        }
                    }
                }

                // 将字形复制到临时图像
                cv::Rect roi(glyph_x, glyph_y, bitmap.width, bitmap.rows);
                if (roi.x >= 0 && roi.y >= 0 && 
                    roi.x + roi.width <= text_overlay.cols && 
                    roi.y + roi.height <= text_overlay.rows) {
                    // 创建目标ROI的引用
                    cv::Mat roi_dst = text_overlay(roi);
                    // 确保源和目标大小匹配
                    if (glyph_bgra.size() == roi_dst.size() && 
                        glyph_bgra.type() == roi_dst.type()) {
                        glyph_bgra.copyTo(roi_dst);
                    } else {
                        LOGE("Size mismatch: glyph_bgra(%dx%d), roi(%dx%d)", 
                             glyph_bgra.cols, glyph_bgra.rows,
                             roi_dst.cols, roi_dst.rows);
                    }
                }
            }

            // 更新基线位置
            baseline_x += (slot->advance.x >> 6);
            baseline_y += (slot->advance.y >> 6);
        }

        // 将文字叠加到原图上
        for (int i = 0; i < img.rows; i++) {
            for (int j = 0; j < img.cols; j++) {
                cv::Vec4b overlay_pixel = text_overlay.at<cv::Vec4b>(i, j);
                if (overlay_pixel[3] > 0) { // 如果alpha通道不为0
                    cv::Vec3b& img_pixel = img.at<cv::Vec3b>(i, j);
                    // Alpha混合
                    float alpha = overlay_pixel[3] / 255.0f;
                    img_pixel[0] = (uchar)((1 - alpha) * img_pixel[0] + alpha * overlay_pixel[0]); // B
                    img_pixel[1] = (uchar)((1 - alpha) * img_pixel[1] + alpha * overlay_pixel[1]); // G
                    img_pixel[2] = (uchar)((1 - alpha) * img_pixel[2] + alpha * overlay_pixel[2]); // R
                }
            }
        }
    }
    
    void Worker::addAlarmVideoFrameQ(Frame* frame) 
    {
        mAlarmVideoFrameQ_mtx.lock();
        mAlarmVideoFrameQ.push(frame);
        mAlarmVideoFrameQ_mtx.unlock();
    }
    
    int Worker::getAlarmVideoFrameQSize()
    {
        int size = 0;
        mAlarmVideoFrameQ_mtx.lock();
        size = mAlarmVideoFrameQ.size();
        mAlarmVideoFrameQ_mtx.unlock();
        return size;
    }

    bool Worker::getAlarmVideoFrame(Frame*& frame) 
    {
        bool res = false;
        if (mAlarmVideoFrameQ_mtx.try_lock()) 
        {
            if (!mAlarmVideoFrameQ.empty()) 
            {
                // 获取报警视频帧
                frame = mAlarmVideoFrameQ.front();
                mAlarmVideoFrameQ.pop();
                res = true;
            }
            mAlarmVideoFrameQ_mtx.unlock();
        }
        return res;
    }

    void Worker::clearAlarmVideoFrameQ() 
    {
        mAlarmVideoFrameQ_mtx.lock();
        while (!mAlarmVideoFrameQ.empty())
        {
            Frame* frame = mAlarmVideoFrameQ.front();
            mAlarmVideoFrameQ.pop();
            mVideoFramePool->giveBack(frame);
        }
        mAlarmVideoFrameQ_mtx.unlock();
    }

    void Worker::calculateTextSize(const std::string& text, int& width, int& height) 
    {
        if (!mFtValid) {
            width = 0;
            height = 0;
            return;
        }

        FT_GlyphSlot slot = mFtFace->glyph;
        width = 0;
        height = 0;
        int max_top = 0;
        
        // 将UTF-8字符串转换为Unicode码点并计算尺寸
        try {
            for (size_t i = 0; i < text.length();) {
                uint32_t unicode = 0;
                unsigned char c = text[i];
                
                if ((c & 0x80) == 0) {
                    unicode = c;
                    i += 1;
                } else if ((c & 0xE0) == 0xC0) {
                    if (i + 1 >= text.length()) break;
                    unicode = ((c & 0x1F) << 6) | (text[i + 1] & 0x3F);
                    i += 2;
                } else if ((c & 0xF0) == 0xE0) {
                    if (i + 2 >= text.length()) break;
                    unicode = ((c & 0x0F) << 12) | 
                             ((text[i + 1] & 0x3F) << 6) | 
                             (text[i + 2] & 0x3F);
                    i += 3;
                } else {
                    i += 1;
                    continue;
                }

                if (FT_Load_Char(mFtFace, unicode, FT_LOAD_RENDER)) {
                    continue;
                }
                width += (slot->advance.x >> 6);
                height = std::max(height, (int)slot->bitmap.rows);
                max_top = std::max(max_top, slot->bitmap_top);
            }
        } catch (const std::exception& e) {
            LOGE("Error parsing UTF-8 string: %s", e.what());
            width = 0;
            height = 0;
            return;
        }

        height = std::max(height, max_top);
    }
}